﻿using System;

using System.Collections.Generic;
using System.Text;
using System.IO;
using PasswordSafe.Properties;

namespace PasswordSafe.Classes
{
    public static class DataReader
    {
        const string FileName = @"\My Documents\passwords.pws";

        public static bool DataBaseExits()
        {
            return File.Exists(FileName);
        }

        public static byte[] ReadData()
        {
            string path = FileName;
            if (File.Exists(path))
            {
                using (FileStream stream = new FileStream(path, FileMode.Open))
                {
                    BinaryReader reader = new BinaryReader(stream);
                    byte[] bytes = reader.ReadBytes((int)stream.Length);
                    return bytes;
                }
            }
            else return null;
        }

        private static void Move(string sourceName, string destName)
        {
            if (File.Exists(destName)) File.Delete(destName);
            File.Move(sourceName, destName);
        }

        public static void WriteData(byte[] data)
        {
            string filename = FileName;
            string altName = GetAltName(filename);
            Move(filename, altName);
            using (FileStream stream = new FileStream(filename, FileMode.Create))
            {
                BinaryWriter writer = new BinaryWriter(stream);
                writer.Write(data);
            }
        }

        private static string GetAltName(string filename)
        {
            string name = Path.GetFileNameWithoutExtension(filename);
            return name + ".bak";
        }

        public static void CreateDatabase()
        {
            string s = Resources.Categories;
            using (StreamWriter writer = File.CreateText(FileName))
            {
                writer.WriteLine(s);
            }
        }
    }
}
